package com.zbkj.service.service.adminregion.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zbkj.common.enums.RegionTypeEnum;
import com.zbkj.common.enums.RoleEnum;
import com.zbkj.common.exception.AppException;
import com.zbkj.common.model.admin.SystemAdmin;
import com.zbkj.common.model.city.CityRegionEntity;
import com.zbkj.common.model.zfbadminregion.ZfbAdminRegion;
import com.zbkj.common.request.PageParamRequest;
import com.zbkj.common.request.SystemAdminRequest;
import com.zbkj.common.request.adminregion.AdminRegionUserAddRequest;
import com.zbkj.common.response.zfbadminregion.ZfbAdminRegionUserResponse;
import com.zbkj.common.result.AdminResultCode;
import com.zbkj.common.result.CommonResultCode;
import com.zbkj.common.utils.CrmebUtil;
import com.zbkj.common.utils.SecurityUtil;
import com.zbkj.common.vo.CityVo;
import com.zbkj.service.dao.CityRegionDao;
import com.zbkj.service.dao.zfbadminregion.ZfbAminRegionMapper;
import com.zbkj.service.service.SystemAdminService;
import com.zbkj.service.service.SystemRoleService;
import com.zbkj.service.service.adminregion.IZfbAdminRegionService;
import com.zbkj.service.util.BrandUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName: ZfbAdminRegionServiceImpl
 * @Description: TODO
 * @Date: 2024/7/28 11:04
 * @Version: V1.0
 **/
@Service
@Slf4j
public class ZfbAdminRegionServiceImpl extends ServiceImpl<ZfbAminRegionMapper, ZfbAdminRegion> implements IZfbAdminRegionService {

    @Autowired
    private IZfbAdminRegionService zfbAdminRegionService;

    @Autowired
    private SystemAdminService systemAdminService;


    @Autowired
    private SystemRoleService systemRoleService;

    @Resource
    private CityRegionDao cityRegionDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean platformSaveAccount(AdminRegionUserAddRequest systemAdminAddRequest) {

        // 管理员名称唯一校验
        if (systemAdminService.checkAccount(systemAdminAddRequest.getAccount())) {
            throw new AppException(AdminResultCode.ADMIN_EXIST);
        }
        if (CollectionUtils.isEmpty(systemAdminAddRequest.getRegionList())) {
            throw new AppException("管理的区域不能为空");
        }

        SystemAdmin systemAdmin = new SystemAdmin();
        BeanUtils.copyProperties(systemAdminAddRequest, systemAdmin);

        String pwd = CrmebUtil.encryptPassword(systemAdmin.getPwd(), systemAdmin.getAccount());
        systemAdmin.setPwd(pwd);
        systemAdmin.setType(RoleEnum.REGION_SUPER_ADMIN.getValue());
        systemAdmin.setRoles(RoleEnum.REGION_SUPER_ADMIN.getValue().toString());
        if (BrandUtil.isBrand()){
            systemAdmin.setBrandId(BrandUtil.getBrandId());
        }
        boolean save = systemAdminService.save(systemAdmin);
        if (!save) {
            throw new AppException("添加失败");
        }
        List<CityRegionEntity> cityRegionList = cityRegionDao.selectList(new LambdaQueryWrapper<CityRegionEntity>()
                .eq(CityRegionEntity::getLevel, RegionTypeEnum.VILLAGE.getValue())
                .in(CityRegionEntity::getDisId, systemAdminAddRequest.getRegionList()));
        if (cityRegionList.size() != systemAdminAddRequest.getRegionList().size()) {
            throw new AppException("选择的区域有误");
        }
        List<ZfbAdminRegion> adminRegions = Lists.newArrayList();
        cityRegionList.forEach(item -> {
            ZfbAdminRegion zfbAdminRegion = new ZfbAdminRegion();
            BeanUtils.copyProperties(item, zfbAdminRegion);
            zfbAdminRegion.setAdminUserId(systemAdmin.getId());
            zfbAdminRegion.setCreateTime(LocalDateTime.now());
            zfbAdminRegion.setUpdateTime(LocalDateTime.now());
            if (BrandUtil.isBrand()){
                zfbAdminRegion.setBrandId(SecurityUtil.getLoginUserVo().getUser().getId());
            }
            adminRegions.add(zfbAdminRegion);
        });
        return zfbAdminRegionService.saveBatch(adminRegions);
    }


    /**
     * 修改账号
     *
     * @param systemAdminAddRequest
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean platformUpdateAccount(AdminRegionUserAddRequest systemAdminAddRequest) {
        SystemAdmin currentUser = SecurityUtil.getLoginUserVo().getUser();

        SystemAdmin adminDetail = systemAdminService.getDetail(systemAdminAddRequest.getId());
        // 超级管理员不允许编辑
        if (adminDetail.getType().equals(RoleEnum.SUPER_ADMIN.getValue())
                || adminDetail.getType().equals(RoleEnum.SUPER_MERCHANT.getValue())) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "系统内置权限，不允许编辑");
        }
        if (!currentUser.getMerId().equals(adminDetail.getMerId())) {
            throw new AppException(AdminResultCode.ADMIN_NOT_EXIST);
        }
        systemAdminService.verifyAccount(systemAdminAddRequest.getId(), systemAdminAddRequest.getAccount());
        SystemAdmin systemAdmin = new SystemAdmin();
        systemAdmin.setId(systemAdminAddRequest.getId());
        systemAdmin.setAccount(systemAdminAddRequest.getAccount());
        systemAdmin.setRealName(systemAdminAddRequest.getRealName());
        systemAdmin.setRoles(systemAdminAddRequest.getRoles());
        systemAdmin.setStatus(systemAdminAddRequest.getStatus());
        if (StrUtil.isNotBlank(systemAdminAddRequest.getPhone())) {
            systemAdmin.setPhone(systemAdminAddRequest.getPhone());
        }
        systemAdmin.setMerId(currentUser.getMerId());
        systemAdminService.updateById(systemAdmin);

        List<CityRegionEntity> cityRegionList = cityRegionDao.selectList(new LambdaQueryWrapper<CityRegionEntity>()
                .eq(CityRegionEntity::getLevel, RegionTypeEnum.VILLAGE.getValue())
                .in(CityRegionEntity::getDisId, systemAdminAddRequest.getRegionList()));
        if (cityRegionList.size() != systemAdminAddRequest.getRegionList().size()) {
            throw new AppException("选择的区域有误");
        }

        List<ZfbAdminRegion> adminRegions = Lists.newArrayList();
        cityRegionList.forEach(item -> {
            ZfbAdminRegion zfbAdminRegion = new ZfbAdminRegion();
            BeanUtils.copyProperties(item, zfbAdminRegion);
            zfbAdminRegion.setAdminUserId(systemAdmin.getId());
            zfbAdminRegion.setCreateTime(LocalDateTime.now());
            zfbAdminRegion.setUpdateTime(LocalDateTime.now());
            adminRegions.add(zfbAdminRegion);
        });
        zfbAdminRegionService.remove(new LambdaQueryWrapper<ZfbAdminRegion>().eq(ZfbAdminRegion::getAdminUserId, systemAdmin.getId()));
        return zfbAdminRegionService.saveBatch(adminRegions);
    }


    /**
     * 后台管理员列表
     *
     * @param request          请求参数
     * @param pageParamRequest 分页参数
     * @return List
     */
    @Override
    public List<ZfbAdminRegionUserResponse> getPlatformList(SystemAdminRequest request, PageParamRequest pageParamRequest) {
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        LambdaQueryWrapper<SystemAdmin> lqw = new LambdaQueryWrapper<>();

        //查询下级用户
        SystemAdmin currentUser = SecurityUtil.getLoginUserVo().getUser();
        if (Objects.equals(currentUser.getType(), RoleEnum.REGION_SUPER_ADMIN.getValue())) {
            lqw.eq(SystemAdmin::getParentId, currentUser.getId());
        }

        if (ObjectUtil.isNotNull(request.getStatus())) {
            lqw.eq(SystemAdmin::getStatus, request.getStatus());
        }
        if (StrUtil.isNotBlank(request.getRealName())) {
            String decode = URLUtil.decode(request.getRealName());
            lqw.and(i -> i.like(SystemAdmin::getRealName, decode)
                    .or().like(SystemAdmin::getAccount, decode));
        }
        lqw.eq(SystemAdmin::getType, RoleEnum.REGION_SUPER_ADMIN.getValue());
        lqw.eq(SystemAdmin::getIsDel, 0);
        if (BrandUtil.isBrand()){
            lqw.eq(SystemAdmin::getBrandId, BrandUtil.getBrandId());
        }
        List<SystemAdmin> systemAdmins = systemAdminService.list(lqw);
        if (CollectionUtils.isEmpty(systemAdmins)) {
            return Lists.newArrayList();
        }
        List<Integer> userIds = systemAdmins.stream().map(SystemAdmin::getId).collect(Collectors.toList());
        LambdaQueryWrapper<ZfbAdminRegion> zfbAdminRegionLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (BrandUtil.isBrand()){
            zfbAdminRegionLambdaQueryWrapper.eq(ZfbAdminRegion::getBrandId, BrandUtil.getBrandId());
            zfbAdminRegionLambdaQueryWrapper.in(ZfbAdminRegion::getAdminUserId, userIds);
        }else{
            zfbAdminRegionLambdaQueryWrapper.in(ZfbAdminRegion::getAdminUserId, userIds);
        }
        List<ZfbAdminRegion> adminRegionList = zfbAdminRegionService.list(zfbAdminRegionLambdaQueryWrapper);
        Map<Integer, List<ZfbAdminRegion>> map = adminRegionList.stream().collect(Collectors.groupingBy(ZfbAdminRegion::getAdminUserId));

        List<ZfbAdminRegionUserResponse> adminResponseList = new ArrayList<>();
        for (SystemAdmin admin : systemAdmins) {
            ZfbAdminRegionUserResponse sar = new ZfbAdminRegionUserResponse();
            BeanUtils.copyProperties(admin, sar);
            List<ZfbAdminRegion> adminRegions = map.get(admin.getId());
            if (!CollectionUtils.isEmpty(systemAdmins)) {
                sar.setRegionList(adminRegions);
            }
            adminResponseList.add(sar);
        }
        return adminResponseList;
    }


    @Override
    public boolean checkIsRegionAdminType(Integer adminType) {
        return false;
    }

    @Override
    public ZfbAdminRegionUserResponse getAdminRegionUser(Integer id) {

        SystemAdmin systemAdmin = systemAdminService.getDetail(id);
        if (Objects.isNull(systemAdmin)) {
            throw new AppException("管理员不存在,参数有误");
        }
        if (!RoleEnum.checkIsRegionAdminUser(systemAdmin.getType())) {
            throw new AppException("不是区域管理员");
        }
        List<ZfbAdminRegion> adminRegionList = zfbAdminRegionService.list(new LambdaQueryWrapper<ZfbAdminRegion>().in(ZfbAdminRegion::getAdminUserId, systemAdmin.getId()));

        ZfbAdminRegionUserResponse userResponse = new ZfbAdminRegionUserResponse();
        BeanUtils.copyProperties(systemAdmin, userResponse);
        userResponse.setRegionList(adminRegionList);
        return userResponse;
    }

    @Override
    public boolean deleteAdminRegionUser(Integer id) {
        SystemAdmin systemAdmin = new SystemAdmin();
        systemAdmin.setId(id);
        systemAdmin.setIsDel(Boolean.TRUE);
        systemAdmin.setUpdateTime(new Date());
        SystemAdmin user = SecurityUtil.getLoginUserVo().getUser();
        systemAdmin.setUpdateUser(user.getAccount());
        zfbAdminRegionService.remove(new LambdaQueryWrapper<ZfbAdminRegion>().eq(ZfbAdminRegion::getAdminUserId, id));
        return systemAdminService.updateById(systemAdmin);
    }


    /**
     * 获取当前用户管理区域
     *
     * @return
     */
    @Override
    public List<CityVo> getCurrentUserRegion() {
        SystemAdmin user = SecurityUtil.getLoginUserVo().getUser();
        List<ZfbAdminRegion> list = zfbAdminRegionService.list(new LambdaQueryWrapper<ZfbAdminRegion>().eq(ZfbAdminRegion::getAdminUserId, user.getId()));

        List<CityVo> cityRtree = Lists.newArrayList();
        Map<String, List<ZfbAdminRegion>> province = list.stream().collect(Collectors.groupingBy(ZfbAdminRegion::getProvinceId));
        province.forEach((k1, v1) -> {
            CityVo provinceVo = new CityVo();
            provinceVo.setRegionId(k1);
            provinceVo.setRegionName(v1.get(0).getProvinceName());
            provinceVo.setRegionType(RegionTypeEnum.PROVINCE.getValue());
            Map<String, List<ZfbAdminRegion>> city = v1.stream().collect(Collectors.groupingBy(ZfbAdminRegion::getCityId));

            List<CityVo> cityList = Lists.newArrayList();
            city.forEach((k2, v2) -> {
                CityVo cityVo = new CityVo();
                cityVo.setRegionId(k2);
                cityVo.setRegionName(v2.get(0).getCityName());
                cityVo.setRegionType(RegionTypeEnum.CITY.getValue());
                cityVo.setParentId(v2.get(0).getProvinceId());
                Map<String, List<ZfbAdminRegion>> district = v2.stream().collect(Collectors.groupingBy(ZfbAdminRegion::getDistrictId));

                List<CityVo> districtList = Lists.newArrayList();
                district.forEach((k3, v3) -> {
                    CityVo districtVo = new CityVo();
                    districtVo.setRegionId(k3);
                    districtVo.setRegionName(v3.get(0).getDistrictName());
                    districtVo.setRegionType(RegionTypeEnum.AREA.getValue());
                    districtVo.setParentId(v3.get(0).getCityId());

                    Map<String, List<ZfbAdminRegion>> town = v3.stream().collect(Collectors.groupingBy(ZfbAdminRegion::getTownId));
                    List<CityVo> townList = Lists.newArrayList();
                    List<CityVo> villageList = Lists.newArrayList();
                    town.forEach((k4, v4) -> {
                        CityVo townVo = new CityVo();
                        townVo.setRegionId(k4);
                        townVo.setRegionName(v4.get(0).getTownName());
                        townVo.setRegionType(RegionTypeEnum.STREET.getValue());
                        townVo.setParentId(v4.get(0).getDistrictId());
                        v4.forEach(item -> {
                            CityVo villageVo = new CityVo();
                            villageVo.setRegionType(RegionTypeEnum.VILLAGE.getValue());
                            villageVo.setRegionId(item.getVillageId());
                            villageVo.setRegionName(item.getVillageName());
                            villageVo.setParentId(item.getTownId());
                            villageList.add(villageVo);
                        });
                        townVo.setChild(villageList);
                        townList.add(townVo);
                    });
                    districtVo.setChild(townList);
                    districtList.add(districtVo);
                });

                cityVo.setChild(districtList);
                cityList.add(cityVo);
            });

            provinceVo.setChild(cityList);

            cityRtree.add(provinceVo);
        });

        return cityRtree;
    }

    private void buildTress(List<ZfbAdminRegion> list) {
        Map<String, CityVo> map = Maps.newHashMap();
        for (ZfbAdminRegion item : list) {
            CityVo cityVo = map.get(item.getProvinceId());
            if (Objects.isNull(cityVo)) {
                cityVo = new CityVo();
            }

        }

    }
}
